package com.ewhale.feitengguest.ui.shop.deal.adapter

import android.os.CountDownTimer
import android.util.SparseArray
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.databinding.ItemDealBinding
import com.ewhale.feitengguest.dto.WaitHandleDto
import com.simga.library.adapter.BindRecycAdapter
import com.simga.library.utils.DateUtil
import com.simga.library.utils.glide.GlideUtil
import java.util.*

/**
 * 作者：SimGa
 * 日期：2020/1/2
 * 时间：11:37
 * 包名：com.ewhale.feitengguest.ui.shop.deal.adapter
 */
class DealAdapter : BindRecycAdapter<ItemDealBinding, WaitHandleDto>() {
    override fun normalViewId(): Int {
        return R.layout.item_deal
    }

    private val mMyTimeList: SparseArray<MyTime>?

    init {
        mMyTimeList = SparseArray()
    }

    override fun onBindViewHolder(mBinding: ItemDealBinding, itemData: WaitHandleDto, holder: RecyclerView.ViewHolder, position: Int) {
        GlideUtil.loadPicture(itemData.headPhoto, mBinding.ivAvatar, R.drawable.default_image)
        mBinding.itemData = itemData
        when (itemData.status) {
            1 -> {
                if (itemData.authEndTime > 0) run {
                    var timer: MyTime? = mMyTimeList!!.get(mBinding.tvOverTime.hashCode())
                    timer?.cancel()
                    val countDown = (itemData.authEndTime * 1000 - Date().time) / 1000
                    timer = MyTime(countDown * 1000, 1000, mBinding.tvOverTime)
                    timer.start()
                    mMyTimeList.put(mBinding.tvOverTime.hashCode(), timer)
                }
            }
            else -> {
                mBinding.tvOverTime.text = itemData.updateTime
                when(itemData.status){
                    2->{mBinding.ivStatus.setImageResource(R.mipmap.d3_ic_shbtg)}
                    3->{mBinding.ivStatus.setImageResource(R.mipmap.d3_ic_shtg)}
                    4->{mBinding.ivStatus.setImageResource(R.mipmap.d3_ic_ygq)}
                }
            }
        }
    }

    private inner class MyTime(millisInFuture: Long, countDownInterval: Long, private val tvOverTime: TextView) : CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            tvOverTime.text = DateUtil.formatSeconds(millisUntilFinished / 1000) + "后自动审核通过"
        }

        override fun onFinish() {
            tvOverTime.text = "审核通过"
        }
    }

    /**
     * 清空当前 CountTimeDown 资源
     */
    fun cancelAllTimers() {
        if (mMyTimeList == null) {
            return
        }
        var i = 0
        val length = mMyTimeList.size()
        while (i < length) {
            val cdt = mMyTimeList.get(mMyTimeList.keyAt(i))
            cdt?.cancel()
            i++
        }
    }
}
